package com.gitee.shigen.gateway.config;

import java.util.Objects;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import reactor.core.publisher.Mono;

/**
 * 限流配置KeyResolver——有三种写法(接口限流/ip限流/用户限流)
 * <a href="https://cloud.tencent.com/developer/article/1953233">参考文章：基于redis的限流方案</a>
 */
@Configuration
public class RateLimitConfig {

    /**
     * 接口限流：根据请求路径限流
     */
    @Bean
    @Primary
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().toString());
    }

    /**
     * 根据请求IP限流
     */
    @Bean
    public KeyResolver ipKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getHostName());
    }

    /**
     * 根据请求参数中的userId进行限流 请求地址写法：http://localhost:8801/rate/123?userId=lisi
     */
    @Bean
    public KeyResolver userKeyResolver() {
        return exchange -> Mono.just(Objects.requireNonNull(exchange.getRequest().getQueryParams().getFirst("userId")));
    }
}
